<?php
/**
 * Flea Site
 *
 * @copyright  Copyright (c) 2008 Movoin Studio (http://movoin.com)
 * @license    Apache License 2.0
 * @version    $Id: Options.php 138 2009-05-25 06:42:38Z movoin $
 */

class Model_Options
{

    var $tblOptions;

    var $_site = 0;

    var $op_fields = 'opt_id, name, value, site_id';

    function Model_Options()
    {
        $this->tblOptions = & FLEA::getSingleton( 'Table_Options' );
    }

    function setSite($siteId)
    {
        $this->_site = $siteId;
    }

    function getSite()
    {
        return $this->_site;
    }

    function getOption($opName=null)
    {
        if($opName) {
            $option = $this->tblOptions->find(array(array('site_id', $this->_site), array('name', trim($opName))), null, $this->op_fields);
        } else {
            $option = $this->tblOptions->findAll(array(array('site_id', $this->_site)), null, null, $this->op_fields);
        }
        if($option) {
            FLEA::loadHelper( 'array' );
            $option = array_to_hashmap(&$option, 'name', 'value');
            return $option;
        }
        return false;
    }

    function setOptions($ops)
    {
        if($options = $this->tblOptions->findAll(array(array('site_id', $this->_site)), null, null, $this->op_fields)) {
            $ops = $this->resumeOptions($ops);
            foreach($options as $key => $option) {
                if($option['name'] == $ops[$key]['name']) {
                    $rows[] = array(
                            'opt_id' => $option['opt_id'],
                            'name' => $option['name'],
                            'value' => $ops[$key]['value'],
                            'site_id' => $this->_site
                        );
                }
            }
            if($this->tblOptions->updateRowset($rows)) {
                return '设置成功!';
            } else {
                return '设置失败!';
            }
        } else {
            foreach($ops as $key => $value) {
                $rows[] = array('name' => $key, 'value' => $value, 'site_id' => $this->_site);
            }
            if($this->tblOptions->createRowset($rows)) {
                return '设置成功!';
            } else {
                return '设置失败!';
            }
        }
    }

    /**
     * 恢复POSTDATA一维数组 为数据库字段 格式的二维数组
     *
     * @param array $post_options
     */
    function resumeOptions($post_options) {
        foreach($post_options as $key => $value) {
            $options[] = array( 'name' => $key, 'value' => $value);
        }
        return $options;
    }

    /**
     * 返回表实例
     *
     */
    function &getTable()
    {
        return $this->tblOptions;
    }
}
